from flask import Flask, jsonify, send_from_directory, request
from note_search import MyNote
import os
import sys

# =======================================================================
# web api
def web_get_all_notes(mynotes):
    result = []
    for h, note in mynotes.notes.items():
        result.append({
            "id": h,
            "path": note["web_path"],
            "last_update_time": note["last_update_time"]
        })
    return result

def web_search_notes(search_text, mynotes):
    return mynotes.search(search_text)



# =======================================================================

note_base_path = "E:/Note"
if len(sys.argv) > 1:
    note_base_path = sys.argv[1].replace("\\", "/")

mynotes = MyNote(note_base_path)
mynotes.cache_notes()

# 创建Flask应用
app = Flask(__name__, static_folder="./static")
# app.config['UPLOAD_FOLDER'] = note_base_path #允许访问其他目录

# 定义API路由

@app.route('/', methods=['GET'])
def index():
    return send_from_directory(os.path.dirname(__file__), "index.html")

@app.route('/note', methods=['GET'])
def note():
    return send_from_directory(os.path.dirname(__file__), "note.html")

@app.route('/note/<id>', methods=['GET'])
def show_note(id):
    return send_from_directory(os.path.dirname(__file__), "note.html")

@app.route('/api', methods=['GET'])
def api():
    return jsonify(message='Hello from API!')

@app.route('/api/get_notes', methods=['GET'])
def get_notes():
    notes = web_get_all_notes(mynotes)
    return jsonify(notes)

@app.route('/api/note/<id>', methods=['GET'])
def get_note(id):
    if id not in mynotes.notes:
        return None
    note_dir = os.path.dirname(mynotes.notes[id]["note_path"])
    note_name = os.path.basename(mynotes.notes[id]["note_path"])
    content = ""
    with open(note_dir+"/"+note_name, "r", encoding='utf-8') as f:
        content = f.read()
    return jsonify({
        "id": id,
        "path": mynotes.notes[id]["web_path"],
        "content": content
    })

@app.route('/api/search', methods=['GET'])
def search():
    search_text = request.args.get('search_text')
    notes = web_search_notes(search_text, mynotes)
    return jsonify(notes)

# 重新缓存note
@app.route('/api/refresh', methods=['GET'])
def refresh():
    mynotes.cache_notes()
    notes = web_get_all_notes(mynotes)
    return jsonify(notes)

# 设置静态资源目录
@app.route('/assets/<path:filename>', methods=['GET'])
def static_files(filename):
    print(filename)
    if ".md" in filename.lower():
        return None
    return send_from_directory(note_base_path, filename)

# 启动Web服务器
if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8000)
